<?php
namespace app\sisome\controller;
use think\Controller;
use think\captcha\Captcha;
use think\Db;
use think\Cache;
// use app\sisome\model\InterfaceCache;
class Interfacecache extends Controller{

    protected $relationSearch = true;
    /**
     * @var \app\sisome\model\InterfaCecache
     * 定时器
     * 第三方接口大满贯
     */
    protected $model = null;

    public function _initialize()
    {   

        if(empty(input())){
            die('非法请求');
        }
        if(input('key') != '123456'){
            die('错误的key值');
        }
        parent::_initialize();
        $this->model = model('InterfaceCache');
    }

    //汇率美元=人民币
    public function exchange_rate()
    {   
        $type = array('type' => '汇率');
        $data = file_get_contents($this->interfa($type['type']));
        $data = json_decode($data,true);

        if($data['resultcode'] != '200'){
            die('接口请求失败');
        }
        $json['type'] = $type['type'];
        $json['json'] = $data['result']['0']['美元']['fBuyPri'] / 100;
        
        $this->add_or_update($type,$json);
       
    }

    // 查询货币涨幅价格
    public function moneyprice()
    {   
        $type = array('type' => '行情');
        $lists = currency(); // 获取设置的货币
        $miu = 0;
        // 货币循环查询走势
        foreach ($lists as $k => $v) {
            $data = file_get_contents($this->interfa($type['type'],$v));
            $data = json_decode($data,true);
            if($data['status'] != 'ok'){
                die('接口请求失败');
            }
            $rmbrate = rmbrate(); // 美元转人民币汇率
            $today_arr = reset($data['data']);
            $yestoday_arr = end($data['data']);
            $today_price = $today_arr['close'];
            $yestoday_price = $yestoday_arr['close'];
            $quotation[$miu]['num'] = round(($today_price - $yestoday_price) / $yestoday_price * 100, 2);// 涨幅
            $quotation[$miu]['today_price'] = $today_price * $rmbrate; // 人民币
            $quotation[$miu]['type'] = $k;
            $miu++;
        }

        $json['type'] = $type['type'];
        $json['json'] = json_encode($quotation);
        $this->add_or_update($type,$json);
       
    }


    // 矿机释放货币
    function mining_machine()
    {
        set_time_limit(0);
       $data =  db('shop_orderform')->where('zt',1)->select();

       $is_userget = '';
       $userget = array();
       if($data){
        foreach($data as  $v){
                // 如果运行开始时间 小于 不运行
                $gettime = (strtotime(date('Y-m-d')) - $v['starttime'])  / 3600;
                // 如果运行周期大于时机设置周期结束运行，
                if($gettime >= $v['yxzq'] * 24 ){
                    $gettime -=$v['yxzq'] * 24;
                    // 如果结算周期大于24小时，跳出循环，结束周期
                    if($gettime > 24){
                        // 结束运行
                        $res = db('shop_orderform')->where('id', $v['id'])->where('zt',1)->update(array('zt' => 2));
                        if($res){
                            db('user')->where('uname',$v['mobile'])->setDec('power',$v['kjsl']);
                        }
                        continue;
                    } 
                    // 获取结算剩余时间
                    $gettime = 24 - $gettime; 
                    
                    $res = db('shop_orderform')->where('id', $v['id'])->where('zt',1)->update(array('zt' => 2));
                    if($res){
                        db('user')->where('uname',$v['mobile'])->setDec('power',$v['kjsl']);
                    }

                }else{
                    if($gettime > 24){
                        $gettime = 24;
                    }
                }

                $get_bi = ($v['capacity'] / ($v['yxzq'] * 24))  * $gettime;
                $userget['uname'] = $v['mobile'];
                $userget['money'] = $get_bi;
                $userget['gettime'] = time();
                $userget['datatype'] = $v['type'];
                $userget['kcid'] = $v['id'];

                $is_userget = db('userget')->where('kcid',$v['id'])->whereTime('gettime','today')->count();

                if(!$is_userget && $get_bi > 0){
                    // 更新收益
                    db('userget')->where('kcid',$v['id'])->insert($userget);
                }
        }
        die('矿机释放货币成功');
       }
       die('暂无矿机释放');
       

      


        
    }
    // 如果矿机在运行，那么计算收益，获利时间 = 释放时间 - 启动时间 ，获利（产币） =  （总币 / 周期 * 24） * 获利时间(转小时)
    // 是否结束运行，结束时间 = 启动时间+周期时间(转时间戳) > 结束时间  那么运行状态已结束 

    // 加载个人用户钱包信息
	public function get_wallet_user()
	{	
        // $userinfo = db('user')->field('id')->select();
        $userinfo = db('user')->alias('u')->join('wallet w','u.id = w.uid')->field('u.id,w.address')->select();

		foreach($userinfo as $v){
            $data = array(); 
			$data['count'] = 0; 
			$data['wallet'] = array(); 
			$contract = contract(); // 合约地址
			$i = 0;
			foreach($contract as $k => $vv){
				$params['contractaddress'] = $vv['contractaddress'];
				$params['address'] = $v['address'];
				$params['unit'] = $vv['unit'];
                $today_price = $this->price($vv['type']);
                $getbalance = getbalance($vv['type'],$params);
                
				$cny = round($getbalance * $today_price,2);
				$data['wallet'][$i]['type'] = $vv['type']; // 类型
				$data['wallet'][$i]['available'] = round($getbalance,2);  // 货币余额
				$data['wallet'][$i]['cny'] = $cny * 1;   //货币汇率
				$data['wallet'][$i]['img'] = $vv['img'];
				$data['count'] += $cny; // 货币累计汇率
				$i++;
			}
			Cache::set('wallet_index'.$v['id'], $data, 180);
        }

        echo '更新用户钱包信息成功';
    }
    
    // 行情提取
	protected function price($type)
	{		
		foreach(moneyprice() as $k => $v)
		{	
			if($v['type'] == $type){
				return $v['today_price'];
			}
		}
		
	}


    // 接口链接数组
    protected function interfa($type, $para = '')
    {
        $url['汇率'] = 'http://web.juhe.cn:8080/finance/exchange/rmbquot?type=1&bank=0&key=e47f4457012e4490d7d9507a00df12e7';
        $url['行情'] = 'http://api.hadax.com/market/history/kline?AccessKeyId=hrfj6yhgg-947a3fe0-6b201048-5fdf0&symbol='.$para.'&period=1day&size=2';
     
        return $url[$type];

    }

    // 调用更新或新增
    protected function add_or_update($type, $json)
    {
        $row = $this->model->get($type);
        if ($row){
            $return = $this->model->where($type)->update($json);
        }else{
            $return = $this->model->save($json);
        }

        if($return){
            die('更新成功');
        }

        die('更新失败，数据未变动');

        // return $return;
    }
    

    
}
